package cn.yuanqiao.common.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zjj
 * @date 2023/9/11
 */
public class ImgUtils {
    private static class ImageType {
        private static final String DEFAULT_NAME = "image";
        private static final String PNG = "png";
        private static final String BASE64_PREFIX = "data:image/png;base64,";
    }
    public static void main(String[] args) throws IOException {
/*<<<<<<< .mine
        List a = cutPic(8,1,"C:\\Users\\Administrator\\Desktop\\22732718107486208001A001_0.jpg" ,"D:\\1");
        System.out.println(JSONArray.from(a).toString());
||||||| .r15601
        List a = cutPic(3,3,"C:\\Users\\Administrator\\Desktop\\导入测试文件\\图.jpg" ,"D:\\1");
        System.out.println(JSONArray.from(a).toString());
=======
        //List a = cutPic(8,1,"C:\\Users\\Administrator\\Desktop\\22732718107486208001A001_0.jpg" ,"D:\\1");
        //System.out.println(JSONArray.from(a).toString());
        //int [] a = imgWidthHeight("C:\\Users\\Lenovo\\Desktop\\22732718107486208001A001_0.jpg");
        //System.out.printf(a.toString());
        File file = new File("C:\\Users\\Lenovo\\Desktop\\22732718107486208001A001_0.jpg");
        System.out.printf(file.getName().substring(0,file.getName().lastIndexOf(".")));
>>>>>>> .r15654*/
    }

    /**
     * 图片分隔
     * @param xNum      横向分割数量
     * @param yNum      纵向分割数量
     * @param input     图像输入路径
     * @param outDir    图片分割保存路径
     * @throws IOException
     */
    public static List<String> cutPic(int xNum, int yNum, String input, String outDir) throws IOException {
        List<String> outImg = new ArrayList<>();
        File fileInput = new File(input);
        BufferedImage img = ImageIO.read(fileInput);
        if (xNum == 0 || yNum == 0 || img == null || outDir == null) {
            return null;
        }

        File file = new File(outDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (!outDir.endsWith("/")) {
            outDir += "/";
        }

        int width = img.getWidth();
        int height = img.getHeight();
        int index = 1;

        for (int n = 1; n <= yNum; n++) {
            int h = height / yNum;
            int y = h * (n - 1);

            for (int m = 1; m <= xNum; m++) {
                int w = width / xNum;
                int x = w * (m - 1);

                BufferedImage resImg = img.getSubimage(x, y, w, h);

                file = new File(outDir+(fileInput.getName().substring(0,fileInput.getName().lastIndexOf(".")))+"_"+index + ".png");
                ImageIO.write(resImg, "png", file);
                outImg.add(fileInput.getParent()+File.separator+(fileInput.getName().substring(0,fileInput.getName().lastIndexOf(".")))+"_"+index + ".png");
                index++;
            }
        }
        return outImg;
    }

    public static int [] imgWidthHeight(String imagePath) throws IOException{
        File imageFile = new File(imagePath);     // 创建图片文件对象
        // 加载图片
        BufferedImage image = ImageIO.read(imageFile);
        int width = image.getWidth();               // 获取图片宽度
        int height = image.getHeight();             // 获取图片高度
        return new int[]{width,height};
    }

    /**
     * 合并任数量的图片成一张图片
     *
     * @param isHorizontal true代表水平合并，false代表垂直合并
     * @param images       待合并的图片数组
     * @return BufferedImage
     */
    public static void mergeImage(boolean isHorizontal, List<String> fileList, String outDir) throws IOException{
        List<BufferedImage> images = new ArrayList<>();
        for(String fileStr:fileList){
            FileInputStream img1 = null;
            BufferedImage image01 = null;
            try {
                img1 = new FileInputStream(fileStr);
                image01 = ImageIO.read(img1);
                images.add(image01);
            }catch (Exception e){

            }finally {
                if(image01 !=null){
                    image01 = null;
                }
                if(img1 != null){
                    img1.close();
                }
            }

        }
        // 生成新图片
        BufferedImage destImage;
        // 计算新图片的长和高
        int allWidth = 0, allHeight = 0, allWidthMax = 0, allHeightMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < images.size(); i++) {
            BufferedImage img = images.get(i);
            allWidth += img.getWidth();
            if (images.size() != i + 1) {
                allHeight += img.getHeight() + 2;
            } else {
                allHeight += img.getHeight();
            }
            if (img.getWidth() > allWidthMax) {
                allWidthMax = img.getWidth();
            }
            if (img.getHeight() > allHeightMax) {
                allHeightMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allWidth, allHeightMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allWidthMax, allHeight, BufferedImage.TYPE_INT_RGB);
        }
        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (BufferedImage img : images) {
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] imageArrayOne = new int[w1 * h1];
            // 逐行扫描图像中各个像素的RGB到数组中
            imageArrayOne = img.getRGB(0, 0, w1, h1, imageArrayOne, 0, w1);
            if (isHorizontal) {
                // 水平方向合并
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(wx, 0, w1, h1, imageArrayOne, 0, w1);
            } else {
                // 垂直方向合并
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(0, wy, w1, h1, imageArrayOne, 0, w1);
            }
            wx += w1;
            wy += h1 + 2;
        }
        writeToFile(outDir,destImage);
        //return destImage;
    }

    /**
     * 保存合并后的图片到文件
     * @param fileName 文件路径名称
     * @param image 图片
     */
    public static void writeToFile(String fileName, BufferedImage image) throws IOException {
        if (fileName == null) {
            fileName = ImageType.DEFAULT_NAME;
        }
        File file = new File(fileName);
        // 保存图片
        ImageIO.write(image, ImageType.PNG, file);
    }
}
